<template>
  <el-dialog :visible="dialogVisible" :title="permissionForm.id ? '编辑权限点':'添加权限点' " :before-close="close">
    <!-- 表单区域 -->
    <el-form ref="permissionRef" :model="permissionForm" :rules="permissionRules" label-width="80px">
      <el-form-item label="权限名称" prop="name">
        <el-input v-model="permissionForm.name" />
      </el-form-item>
      <el-form-item label="权限标识" prop="code">
        <el-input v-model="permissionForm.code" />
      </el-form-item>
      <el-form-item label="权限描述">
        <el-input v-model="permissionForm.description" />
      </el-form-item>
      <el-form-item label="权限启用">
        <el-switch
          v-model="permissionForm.enVisible"
          active-value="1"
          inactive-value="0"
          active-text="启用"
          inactive-text="不启用"
        />
      </el-form-item>
    </el-form>
    <!-- 按钮区域 -->
    <template #footer>
      <div style="text-align: right;">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { addPermission, getPermissionById, updatePermission } from '@/api'
export default {
  name: 'PermissionDialog',

  /** ******** 父传子数据接收 **********/
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    type: {
      type: Number,
      default: 1
    },
    pid: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      permissionForm: {
        enVisible: 1, // 权限启用标识
        name: '', // 权限名称
        code: '', // 权限标识
        description: '' // 权限描述
      },
      permissionRules: {
        name: [{ required: true, message: '请填写权限名称', trigger: 'blur' }],
        code: [{ required: true, message: '请填写权限标识', trigger: 'blur' }]
      }
    }
  },

  methods: {
    handleClose() {
      this.$emit('handleClose')
    },
    close() {
      this.$emit('close')
      // 数据重置
      this.$refs.permissionRef.resetFields()
      // 手动重置
      this.permissionForm = {
      }
    },
    submit() {
      const data = {
        ...this.permissionForm,
        pid: this.pid,
        type: this.type
      }
      //   // 兜底校验
      this.$refs.permissionRef.validate(async(valid) => {
        if (!valid) return false
        if (this.permissionForm.id) {
          await updatePermission(this.permissionForm)
        } else {
          await addPermission(data)
        }

        this.$message.success(`${this.permissionForm.id ? '编辑权限成功' : '添加权限成功'}`)
        this.close()
        this.$emit('update')
      })
    },
    // 数据回显
    async getDetail(id) {
      const res = await getPermissionById(id)
      this.permissionForm = res.data
    }
  }
}

</script>
<style lang='less' scoped>
</style>
